package com.common.exception;

import com.common.util.SecreUtil;
import org.apache.log4j.Logger;
//import com.oauth.error.ErrorModel;
//import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
//import org.apache.oltu.oauth2.common.exception.OAuthRuntimeException;
//import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
//import org.springframework.http.HttpStatus;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 异常处理
 * Created by yangjianbo on 2016/9/27.
 */
@ControllerAdvice
public class HandlException {

    @Value("${shiro.loginUrl}")
    private String loginUrl;

    private String ajaxAuthFailer="auth/failed";

    private Logger logger =  Logger.getLogger(HandlException.class);

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @Autowired
    private ExceptionLog exceptionLog;
//    @ExceptionHandler(OAuthProbl emException.class)
//    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
//    @ResponseBody
//    public ErrorModel deal(OAuthProblemException ex) {
//        logger.error(ex.getMessage(), ex);
//        logger.info("*************OAuthProblemException ------ 异常信息已记录（" + new Date().toString()+ "） ------- ***********");
//        return new ErrorModel(ex.getError(),ex.getDescription());
//    }
//
//    @ExceptionHandler(OAuthRuntimeException.class)
//    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
//    @ResponseBody
//    public String deal(OAuthRuntimeException ex) {
//        logger.error(ex.getMessage(), ex);
//        logger.info("*************OAuthRuntimeException ------ 异常信息已记录（" + new Date().toString()+ "） ------- ***********");
//        return ex.getMessage();
//    }
//
//    @ExceptionHandler(OAuthSystemException.class)
//    @ResponseStatus(code = HttpStatus.UNAUTHORIZED)
//    @ResponseBody
//    public String deal(OAuthSystemException ex) {
//        logger.error(ex.getMessage(), ex);
//        logger.info("*************OAuthSystemException ------ 异常信息已记录（" + new Date().toString()+ "） ------- ***********");
//        return ex.getMessage();
//    }

    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(code = HttpStatus.EXPECTATION_FAILED)
    @ResponseBody
    public String operateSimple(BusinessException exception){
        logger.warn("simple 异常 [ " + exception.getMessage() + "]");
//        String logId=(String)SecreUtil.getSessionValue("logId");
//        exceptionLog.log(logId,exception.getErrMsg(),exception.getErrCode());
        return exception.getErrMsg();
    }

    @ExceptionHandler(AuthenticationException.class)
    @ResponseStatus(code = HttpStatus.EXPECTATION_FAILED)
    @ResponseBody
    public String operateUser(AuthenticationException exception){
        return exception.getMessage();
    }

    @ExceptionHandler(UnauthenticatedException.class)
    public String operateExp(UnauthenticatedException ex) {
        logger.error(ex.getMessage(), ex);
        logger.info("*************RuntimeException ------ 异常信息已记录（" + new Date().toString()+ "） ------- ***********");
        String logId=(String)SecreUtil.getSessionValue("logId");
        exceptionLog.log(logId,ex.getMessage(),"unauth");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String requestType = request.getHeader("X-Requested-With");
        logger.info("请求类型：：："+requestType);
        if("XMLHttpRequest".equals(requestType)){
            return "redirect:"+this.ajaxAuthFailer;
        }
        WebUtils.saveRequest(request);
        return "redirect:"+this.loginUrl;
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(code = HttpStatus.EXPECTATION_FAILED)
    @ResponseBody
    public String deal(RuntimeException ex) {
        logger.error(ex.getMessage(), ex);
        logger.info("*************RuntimeException ------ 未处理异常--请联系开发人员（" + new Date().toString()+ "） ------- ***********");
        String logId=(String)SecreUtil.getSessionValue("logId");
        exceptionLog.log(logId,"系统异常","999");
        return "出现未授检测异常，请联系开发人员，提高系统稳定性";
    }

    @ExceptionHandler(MultipartException.class)
    @ResponseStatus(code = HttpStatus.EXPECTATION_FAILED)
    @ResponseBody
    public String operateUpload(MultipartException ex) {
        return "图片大于1MB，请重处理后再传";
    }

}
